package chat.server;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ChatServer {
	private int serverPort =0;	
	private CountDownLatch latch = null;
	private ExecutorService chatpool = null;
	
	/**
	 * Constructor for the chat server
	 * @param port
	 */
	public ChatServer (int port){
		this.serverPort = port;
		chatpool = Executors.newFixedThreadPool(10);
	}
	/**
	 * Starts the server with the given port and waits for the client to connect.
	 * 
	 */
	public void serverStart() {
		try {
			//creates the server socket for the port.
			ServerSocket ssock = new ServerSocket(this.serverPort);
			System.out.println("Server listening ......");
			while(true){
				Socket socket = ssock.accept();
				// A dispatcher which is a light weight thread.
				// sends the from user conversation to toUser.
				Chat c = new Chat(socket);
				chatpool.submit(c);				
			}
		} catch (Exception e)	{
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args){
		if(args == null || args.length != 1) {
			System.out.println("Invalid Argument : Usage java ChatServer <port>");
			System.exit(0);
		}
		ChatServer server = new ChatServer(Integer.parseInt(args[0]));
		server.serverStart();
	}
}